package backend.Instruction;

import backend.component.RISCVimm;
import backend.Register.RISCVoperand;

import java.util.List;

public class RISCVbinary extends RISCVinst {
    private List<RISCVoperand> operands;
    private String type;
    public RISCVbinary(List<RISCVoperand> operands) {
        this.operands = operands;
    }

    public RISCVbinary(String type,List<RISCVoperand> operands) {
        this.operands = operands;
        this.type = type;
        setDst(operands.get(0));
        setSrcLeft(operands.get(1));
        setSrcRight(operands.get(2));
    }
    public void setDst(RISCVoperand dst) {
        setDefReg(operands.get(0), dst);
        operands.set(0, dst);
    }

    public void setSrcLeft(RISCVoperand src1) {
        addUseReg(operands.get(1), src1);
        operands.set(1, src1);
    }

    public void setSrcRight(RISCVoperand src2) {
        addUseReg(operands.get(2), src2);
        operands.set(2, src2);
    }
    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public RISCVoperand getDst() {
        return operands.get(0);
    }

    public RISCVoperand getSrc1() {
        return operands.get(1);
    }

    public RISCVoperand getSrc2() {
        return operands.get(2);
    }

    public boolean isSrc2Imm12() {
        return operands.get(2) instanceof RISCVimm && ((RISCVimm) operands.get(2)).getIs();
    }
    public void replaceReg(RISCVoperand oldReg, RISCVoperand newReg) {
        if (operands.get(0).equals(oldReg)) {
            setDst(newReg);
        }
        if (operands.get(1).equals(oldReg)) {
            setSrcLeft(newReg);
        }
        if (operands.get(2).equals(oldReg)) {
            setSrcRight(newReg);
        }
    }



    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(type);
        //如果是立即数的操作 需要加上  i
        if(isSrc2Imm12() &&
                (type.equals("add") || type.equals("xor") || type.equals("or") || type.equals("and") ||
                type.equals("sll") || type.equals("srl") || type.equals("sra"))){
            sb.append("i");
        }
        sb.append(" ").append(operands.get(0)).append(", ").append(operands.get(1)).append(", ").append(operands.get(2)).append("\n");
        return sb.toString();
    }
}
